package com.example.myapplication

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var textView = findViewById<TextView>(R.id.result)
        findViewById<Button>(R.id.run1).setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                for (i in 1..10) {
                    var runCommand =
                        RootCommand.runCommand(this@MainActivity,"ifconfig eth0 172.31.3.49 netmask 255.255.255.0 " +
                                "broadcast 239.127.3.1")
                    delay(50)
                    if (RootCommand.runCommand(this@MainActivity, "ifconfig").contains("172.31.3.49")) {
                        break
                    }
                    textView.text = runCommand
                }
            }.start()
        }

        findViewById<Button>(R.id.run2).setOnClickListener {
            var runCommand =
                RootCommand.runCommand(this,"ifconfig eth0 172.31.3.49")
            textView.text = runCommand
        }
        findViewById<Button>(R.id.edit_mac).setOnClickListener {
            RootCommand.runCommand(this@MainActivity,"ifconfig eth0 172.31.3.49 netmask 255.255.255.0 " +
                    "broadcast 239.127.3.1")
                RootCommand.runCommand(this@MainActivity,"ifconfig eth0 down")
                RootCommand.runCommand(this@MainActivity,"ifconfig eth0 hw ether 02:80:5e:1f:01:53")
                RootCommand.runCommand(this@MainActivity,"ifconfig eth0 up")

        }
        findViewById<Button>(R.id.run3).setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                for (i in 1..10) {
                    var runCommand =
                        RootCommand.runCommand(this@MainActivity,"ifconfig eth0 172.31.3.49 netmask 255.255.255.0")
                    delay(50)
                    if (RootCommand.runCommand(this@MainActivity, "ifconfig").contains("172.31.3.49")
                        && !RootCommand.runCommand(this@MainActivity, "ifconfig").contains("239.127.3.1")
                    ) {
                        break
                    }
                    textView.text = runCommand
                }
            }.start()
        }

        findViewById<Button>(R.id.btn1).setOnClickListener {
            var runCommand = RootCommand.runCommand(this, "ifconfig")
            textView.text = runCommand
        }
    }
}